package csm.web.core.search.IR;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import csm.common.StringUtil;
import csm.common.net.HttpRequester;
import csm.web.core.RequestHelper;
import csm.web.core.search.ISearchCommand;
import csm.web.core.search.SearchResultInfo;

public class IRSearchCommand implements ISearchCommand {

	@Override
	public SearchResultInfo doSearch(RequestHelper req) throws Exception {
		HttpURLConnection cn = null;

		String query = req.getParameter("q");

		if( StringUtil.isNullOrEmpty(query))
			return new IRSearchResult();

		int pageSize = req.getIntParameter("pageSize", 10);
		int page = req.getIntParameter("page", 1);
		int startRow = (page -1) * pageSize;

		if( pageSize <= 0)
			pageSize = 10;

		//System.out.println("q param => " + query);
		//System.out.println("pageSize param => " + pageSize);
		//System.out.println("page param => " + page);
		//System.out.println("startRow => " + startRow);


		//TODO 환경설정에서 가져와야 한다
		//http://1.215.238.28:7788/solr/
		String uri = "http://1.215.238.28:7788/solr/select";
		IRSearchResult result = new IRSearchResult();
		result.setQuery(query);
		try {

			HttpRequester hq = new HttpRequester();

			hq.setConnectTimeout(10000);
			hq.setReadTimeout(20000);
			hq.appendParameter("q", URLEncoder.encode(query, "EUC-KR"));
			hq.appendParameter("start", String.valueOf(startRow));
			hq.appendParameter("rows", String.valueOf(pageSize));

			String cmd = hq.getParameterQuery();

			System.out.println("SOLR Search CMD:" + uri + "?" + cmd);
			String resultStr = hq.executeString( uri + "?" + cmd);


			result.parseResult(resultStr);
			result.setEngineQuery(cmd);
			return result;

		} catch (MalformedURLException e) {
			throw e;
		} catch (IOException e) {
			throw e;
		} catch (Exception e) {
			throw e;
		} finally {
			if (cn != null)
				cn.disconnect();
		}
	}
	public SearchResultInfo doSearch2(RequestHelper req) throws Exception {
		HttpURLConnection cn = null;

		String query = req.getParameter("q");

		int pageSize = req.getIntParameter("pageSize", 10);
		int page = req.getIntParameter("page", 1);
		int startRow = (page -1)*pageSize;

		//System.out.println("q param =" + query);
		//System.out.println("pageSize param =" + pageSize);
		//System.out.println("page param =" + page);

		if(page > 0)
			page = page -1;// 1페이지는 검색엔진에 0페이지로 요청해야 한다.

		//TODO 환경설정에서 가져와야 한다
		String uri = "http://192.168.0.32:9001/solr/select";


		try {

			String cmd = StringUtil.format("q={0}&start={1}&rows={2}", query == null ? "null" : URLEncoder.encode( query , "UTF-8"), startRow, pageSize);
			URL url = new URL(uri + "?" + cmd);
			cn = (HttpURLConnection) url.openConnection();

			/*
			String cmd = StringUtil.format("q={0}&start={1}&rows={2}", query, startRow, pageSize);
			URL url = new URL(uri);
			cn = (HttpURLConnection) url.openConnection();

			// POST방식으로 검색명령 전송 (UTF-8)
			cn.setConnectTimeout(10000);
			cn.setReadTimeout(20000);
			cn.setDoOutput(true);

			OutputStream out = cn.getOutputStream();
			out.write(cmd.replaceAll("\\+", "%2B").getBytes("utf-8"));
			out.close();
			*/


			// 결과 수신
			BufferedReader br = new BufferedReader(new InputStreamReader(cn.getInputStream(), "UTF-8"));
			String inputLine;
			StringBuffer sb = new StringBuffer();
			while ((inputLine = br.readLine()) != null)
				sb.append(inputLine).append('\n');

			System.out.println("cmd =" + cmd);

			IRSearchResult result = new IRSearchResult();
			result.parseResult(sb.toString());
			result.setEngineQuery(cmd);
			return result;

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (cn != null)
				cn.disconnect();
		}

		return null;
	}
}
